package com.aube.multiscreen;

import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.ValueAnimator;
import android.app.Activity;
import android.content.Context;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.Surface;
import android.view.TextureView;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.asha.vrlib.texture.GLTextureView;
import com.aube.R;
import com.aube.control.player.AbstractVideoHelper;
import com.aube.control.player.ISurfaceTextureProvider;
import com.aube.control.player.MajorTextureVideoHelper;
import com.aube.control.player.MajorVRTextureVideoHelper;
import com.aube.control.player.TextureVideoHelper;
import com.aube.guide.GuideConstants;
import com.aube.model.VideoItem;
import com.aube.model.VrItem;
import com.aube.views.RingLoading;
import com.aube.views.vote.AnimatorHelper;
import com.huyn.baseframework.model.VideoPlayModel;
import com.huyn.baseframework.utils.Utils;

import java.util.concurrent.atomic.AtomicBoolean;

/**
 * Created by huyaonan on 16/6/27.
 * 普通视频附带vr视频的状况
 */
public class VRMixedCardView extends VRCardView {

    private static final int STATE_UNKNOWN = 0;
    private static final int STATE_INITED = 1;
    private static final int STATE_DESTROYED = 2;
    private static final int STATE_REPLACING = 3;
    private int mVrVideoMode = STATE_UNKNOWN;

    private LinearLayout mVrViewLayout;

    private TextureView mTextureView;

    protected AbstractVideoHelper mVrHelper;

    private AtomicBoolean mIsAnimating = new AtomicBoolean(false);

    private AtomicBoolean mPauseByVr = new AtomicBoolean(false);

    private AtomicBoolean mVrDisplayed = new AtomicBoolean(false);

    private AbstractVideoHelper mMajorVideoHelper;

    private VrItem mVrData;

    public VRMixedCardView(Context context) {
        this(context, null);
    }

    public VRMixedCardView(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public VRMixedCardView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    protected void inflateView() {
        LayoutInflater.from(context).inflate(R.layout.layout_vr_mixed_card, this);
        mRoot = findViewById(R.id.card_layout);
        mTool = findViewById(R.id.card_tools);

        mVideoBg = findViewById(R.id.card_bg);

        mTextureView = (TextureView) findViewById(R.id.card_video);
        mVrViewLayout = (LinearLayout) findViewById(R.id.card_video_layout);

        mToolLayout = findViewById(R.id.card_tool_layout);
        mGesture = (ImageView) findViewById(R.id.card_gesture);
        mGlass = (ImageView) findViewById(R.id.card_glass);

        mZoom = (ImageView) findViewById(R.id.card_zoom);
        mClose = (ImageView) findViewById(R.id.card_close);

        mAudioMask = findViewById(R.id.card_audio_mask);
        mVoice = (ImageView) findViewById(R.id.card_voice_toggle);
        mVoice.setTag(R.id.video_voice, false);

        mTitle = (TextView) findViewById(R.id.card_title);
        mDes = (TextView) findViewById(R.id.card_des);

        mLoading = (RingLoading) findViewById(R.id.card_loading);
    }

    private void attachGLTextureView() {
        Utils.Log(TAG, "VR..........add GLTextureView");
        if(mVrViewLayout.getChildCount() > 0)
            return;
        mVrView = new GLTextureView(getContext());
        mVrViewLayout.addView(mVrView, new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
//        prepareVrLibrary();
    }

    private void removeGLTextureView() {
        Utils.Log(TAG, "VR..........remove GLTextureView");
        mVrViewLayout.removeAllViews();
    }

    public boolean isVr() {
        if(mVrHelper != null)
            return true;
        return false;
    }

    public void hideTitle(boolean showTopTool) {
        mTool.setVisibility(View.VISIBLE);
        mDes.setVisibility(View.VISIBLE);

        mTitle.setVisibility(View.GONE);
        mToolLayout.setVisibility(View.GONE);
        if (showTopTool) {
            mClose.setVisibility(View.VISIBLE);
        } else {
            mClose.setVisibility(View.GONE);
        }
    }

    public void showTitle() {
        AnimatorHelper.alphaAnim(mTool, 0f, 1f);

        mClose.setVisibility(View.GONE);
        mToolLayout.setVisibility(View.VISIBLE);
        mTitle.setVisibility(View.VISIBLE);
        mDes.setVisibility(View.GONE);

        if(isVr()) {
            postDelayed(new Runnable() {
                @Override
                public void run() {
                    GuideConstants.showVrGuide((Activity) getContext(), VRMixedCardView.this, supportVRMotionMode(), null);
                }
            }, 500);
        }
    }

    public void hideAll() {
        mTool.setVisibility(View.GONE);

        mClose.setVisibility(View.GONE);
        mToolLayout.setVisibility(View.GONE);
        mTitle.setVisibility(View.GONE);

        mDes.setVisibility(View.GONE);
    }

    public void manageStateInPIP(boolean showDes) {
        mTool.setVisibility(View.VISIBLE);
        mClose.setVisibility(View.VISIBLE);
        mTitle.setVisibility(View.GONE);
        mToolLayout.setVisibility(View.GONE);

        if (showDes) {
            mDes.setVisibility(View.VISIBLE);
        } else {
            mDes.setVisibility(View.GONE);
        }
    }

    /**
     * 重置主镜头的声音相关东西
     */
    public void resetSoundState() {
        if(isVr()) {
            if(mVrHelper != null)
                mVrHelper.manageSound(true);
            if(mHelper != null)
                mHelper.manageSound(false);
        } else {
            if(mHelper != null)
                mHelper.manageSound(true);
        }
        showBorder(false);
        mVoice.setVisibility(View.GONE);
        mAudioMask.setVisibility(View.GONE);
    }

    public void soundOff() {
        if(isVr() && mVrHelper != null)
            mVrHelper.manageSound(false);
        super.soundOff();
    }

    public boolean isSoundOn() {
        boolean isSoundOn = false;
        if(mHelper != null)
            isSoundOn = mHelper.isSoundOn();
        if(mVrHelper != null)
            isSoundOn |= mVrHelper.isSoundOn();
        return isSoundOn;
    }

    /**
     * 声音开关
     * @param soundOn
     */
    public void manageSound(boolean soundOn) {
        if(isVr()) {
            if(mVrHelper != null)
                mVrHelper.manageSound(soundOn);
            mHelper.manageSound(false);
        } else
            mHelper.manageSound(soundOn);
    }

    public AbstractVideoHelper play(final int i, VideoItem item, final long startTime, boolean play, final IVideoController controller) {
        mHelper = new TextureVideoHelper(mTextureView, context, item.getVideo());
        mHelper.setStartTime(startTime);
        mHelper.initPlayState(play);
        mHelper.setPlayCallback(new AbsPlayCallback() {
            @Override
            public void endPlay() {
                hideLoading();
            }

            @Override
            public void updatePlay(long current, long duration) {
                if (lastPosition == current) {
                    showLoading();
                } else {
                    hideLoading();
                    lastPosition = current;
                }

                if (current > 500) {
                    //显示声音图标
                    if (mVideoPrepared.get())
                        return;
                    //show voice and mask
                    mVideoPrepared.set(true);

                    //show voice icon if needed
                    managePadding(true);
                }
            }

            @Override
            public void clearLoading() {
                hideLoading();
            }
        });

        showLoading();
        initContent(item, i, controller);
        return mHelper;
    }

    /**
     * 插入vr视频并且暂停所有视频,并锁定
     * @param videoItem
     * @param startTime
     * @param play
     */
    private void prepareVrVideoHelper(VrItem videoItem, long startTime, boolean play) {
//        suspendAllPlayers();
        attachGLTextureView();
        this.mVrData = videoItem;
        prepareVrLibrary();
        if(mVrData != null)
            mVRLibrary.updateAngleXY(mVrData.getAngleXY());

        mSurfaceFilled.set(false);
        mVrHelper = new MajorVRTextureVideoHelper(context, videoItem.getVideo(), false, new ISurfaceTextureProvider() {
            @Override
            public Surface getSurface() {
                Utils.Log(TAG, "VR..........getSurface in CardView");
                if(mVRLibrary != null) {
                    Utils.Log(TAG, "VR..........getSurface is not null:" + (mVRLibrary.getSurface()==null));
                    return mVRLibrary.getSurface();
                }
                return null;
            }
        }, null);
        mVrHelper.setStartTime(startTime);
        mVrHelper.initPlayState(play);
        mVrHelper.setPlayCallback(new AbsPlayCallback() {
            @Override
            public void endPlay() {
                hideLoading();

                detachVrVideo();
            }

            @Override
            public void updatePlay(long current, long duration) {
                if (lastPosition == current) {
                    showLoading();
                } else {
                    hideLoading();
                    lastPosition = current;
                }
//                if (current > 500) {
//                    //显示声音图标
//                    if (mVideoPrepared.get())
//                        return;
//                    //show voice and mask
//                    mVideoPrepared.set(true);
//
//                    //show voice icon if needed
//                    managePadding(true);
//                }
//                Utils.Log(TAG, "progress..." + current);
                if(current > 200) {
                    if(mTargetPosition > 0) {
                        if(mVrHelper != null)
                            mVrHelper.seekTo(mTargetPosition);
                        Utils.Log(TAG, "VR..........do seek..." + mTargetPosition);
                        mTargetPosition = -1;
                    }

                    //show vrview and play all views
                    if(mVrDisplayed.get())
                        return;

                    if(!mVrShowTimeReached.get()) {
                        Utils.Log(TAG, "VR..........pause vr player..." + current);
                        mVrPrepared.set(true);
                        if(mVrHelper != null)
                            mVrHelper.pausePlay();
                        showLoading();
                        return;
                    }

                    showVrView();

                    notifyAllPlayers();

                    if(mVRLibrary != null && mVRLibrary.getSurface() != null) {
                        Utils.Log(TAG, "VR..........updatePlay");
                        updateSurface(mVRLibrary.getSurface());
                    }

                    if(mHelper.isSoundOn()) {
                        if(mVrHelper != null)
                            mVrHelper.manageSound(true);
                        mHelper.manageSound(false);
                    }

                    mVideoBg.setVisibility(GONE);

                    GuideConstants.showVrGuide((Activity) getContext(), VRMixedCardView.this, supportVRMotionMode(), null);
                }
            }

//            @Override
//            public void clearLoading() {
//                hideLoading();
//            }
//
//            @Override
//            public void syncSuccess() {
//                showVrView();
//            }


            @Override
            public boolean hasFocused() {
                return true;
            }
        });

        //防止surface为空播放不出来
        if(mVRLibrary != null && mVRLibrary.getSurface() != null) {
            Utils.Log(TAG, "VR..........prepareVrVideoHelper");
            updateSurface(mVRLibrary.getSurface());
        }

        postDelayed(new Runnable() {
            @Override
            public void run() {
                showLoading();
            }
        }, 100);
    }

    /**
     * 暂停所有视频
     */
    public void suspendAllPlayers() {
        if(iController != null)
            iController.suspendAllPlayers();
        mPauseByVr.set(true);
    }

    /**
     * 重启所有视频
     */
    private void notifyAllPlayers() {
        if(iController != null)
            iController.notifyAllPlayers();
        mPauseByVr.set(false);
    }

    /**
     * vr和普通视频切换
     */
    private void showVrView() {
        if(mIsAnimating.get())
            return;
        mIsAnimating.set(true);
        mVrDisplayed.set(true);

        //改变主界面的工具条样式
        if(iController != null)
            iController.initToolBar(false);

        mGesture.setVisibility(View.VISIBLE);
        mGlass.setVisibility(View.VISIBLE);
        ValueAnimator anim = ValueAnimator.ofFloat(0f, 1f);
        anim.setDuration(300);
        anim.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                float value = (float) animation.getAnimatedValue();
                mTextureView.setAlpha(1-value);

                mGesture.setAlpha(value);
                mGlass.setAlpha(value);
            }
        });
        anim.addListener(new AnimatorListenerAdapter() {
            @Override
            public void onAnimationEnd(Animator animation) {
                mIsAnimating.set(false);
            }
        });
        anim.start();
    }

    private void hideVrView() {
        if(!mVrDisplayed.get()) {
            //改变主界面的工具条样式
            if(iController != null)
                iController.initToolBar(false);
            if(mVrHelper != null) {
                mSurfaceFilled.set(false);
                mVrHelper.setPlayCallback(null);
                mVrHelper.onDestroy();
                mVrHelper = null;
            }
            notifyAllPlayers();
            return;
        }
        if(mIsAnimating.get())
            return;
        mIsAnimating.set(true);
        mVrDisplayed.set(false);

        if(mVrHelper != null)
            mVrHelper.setPlayCallback(null);

        ValueAnimator anim = ValueAnimator.ofFloat(0f, 1f);
        anim.setDuration(300);
        anim.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                float value = (float) animation.getAnimatedValue();
                mTextureView.setAlpha(value);

                mGesture.setAlpha(1-value);
                mGlass.setAlpha(1-value);
            }
        });
        anim.addListener(new AnimatorListenerAdapter() {
            @Override
            public void onAnimationEnd(Animator animation) {
                mGesture.setVisibility(View.GONE);
                mGlass.setVisibility(View.GONE);

                if(mVrHelper != null) {
                    mVrHelper.onDestroy();
                    mVrHelper = null;
                }
                mIsAnimating.set(false);

                //改变主界面的工具条样式
                if(iController != null)
                    iController.initToolBar(false);

                removeGLTextureView();
            }
        });
        anim.start();
    }

    public AbstractVideoHelper getVideoHelper(VideoPlayModel video, String x, String y, AbsPlayCallback playCallback) {
        mMajorVideoHelper = new MajorTextureVideoHelper(mTextureView, context, video, playCallback);
        return mMajorVideoHelper;
    }

    protected void updateSurface(Surface surface) {
        Utils.Log(TAG, "VR MIX..........update vr surface");
        if(mSurfaceFilled.get() || surface == null)
            return;
        if(mVrHelper != null) {
            Utils.Log(TAG, "VR MIX..........update vr surface in mVrHelper");
            mVrHelper.updateSurface(surface);
            mSurfaceFilled.set(true);
        }
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        if(mVRLibrary != null && mVrHelper != null)
            return mVRLibrary.handleTouchEvent(event) || super.onTouchEvent(event);
        return super.onTouchEvent(event);
    }

    /**
     * 初始化vr镜头并在特定的时间点播放
     */
    private AtomicBoolean mVrShowTimeReached = new AtomicBoolean(false);
    private AtomicBoolean mVrPrepared = new AtomicBoolean(false);
    private int mTargetPosition = -1;
    public void attachVrVideo(VrItem vr, long startTime) {
        if(mIsAnimating.get())
            return;
        if(mVrVideoMode == STATE_INITED) {
            displayAndBlockMain(vr, startTime);
            return;
        }
        mVrVideoMode = STATE_INITED;
        mVrData = vr;
        mTargetPosition = (int) (startTime - vr.startSeconds) * 1000;
        if(mTargetPosition < 0)
            mTargetPosition = 0;
        prepareVrVideoHelper(vr, startTime, true);
        Utils.Log(TAG, "VR..........load vr..."+startTime + "---" + mTargetPosition);

        displayAndBlockMain(vr, startTime);
    }

    private void displayAndBlockMain(VrItem vr, long startTime) {
        if(vr.startSeconds <= startTime) {
            if (!mVrShowTimeReached.get()) {
                mVrShowTimeReached.set(true);

                if(mVrPrepared.get()) {
                    Utils.Log(TAG, "VR..........resume vr player");
                    if(mVrHelper != null)
                        mVrHelper.startPlay();
                    if(mHelper.isSoundOn()) {
                        if(mVrHelper != null)
                            mVrHelper.manageSound(true);
                        mHelper.manageSound(false);
                    }
                } else {
                    Utils.Log(TAG, "VR..........pause main player");
                    suspendAllPlayers();
                }
            } else {

            }
        }
    }

    public void replaceVrVideo(VrItem vr, long startTime) {
        if(mIsAnimating.get())
            return;
        if(mVrVideoMode == STATE_REPLACING)
            return;
        mVrVideoMode = STATE_REPLACING;
        mVrData = vr;
        mTargetPosition = (int) (startTime - vr.startSeconds) * 1000;
        if(mTargetPosition < 0)
            mTargetPosition = 0;
        if(mVrHelper != null) {
            mVrHelper.setPlayCallback(null);
            mVrHelper.onDestroy();
            mVrHelper = null;

            if(mVrHelper.isSoundOn()) {
                mHelper.manageSound(true);
                mVrHelper.manageSound(false);
            }
        }
        prepareVrVideoHelper(vr, startTime, true);
        mVrPrepared.set(false);
        mVrShowTimeReached.set(false);
        mVrVideoMode = STATE_INITED;
        Utils.Log(TAG, "VR..........replace vr..."+startTime);
        displayAndBlockMain(vr, startTime);
    }

    /**
     * 移除vr镜头
     */
    public void detachVrVideo() {
        if(mIsAnimating.get())
            return;
        if(mVrVideoMode == STATE_DESTROYED)
            return;
        mVrVideoMode = STATE_DESTROYED;
        mTargetPosition = -1;
        mVrPrepared.set(false);
        mVrShowTimeReached.set(false);
        if(mVrHelper == null)
            return;
        if(mVrHelper.isSoundOn()) {
            mHelper.manageSound(true);
            mVrHelper.manageSound(false);
        }
        mVrData = null;
        hideVrView();
//        notifyAllPlayers();
        Utils.Log(TAG, "VR..........remove vr");
    }

    @Override
    public void suspendPlayer() {
//        super.suspendPlayer();
        //还要暂停其他view的vr
        mMajorVideoHelper.pausePlay();
    }

    @Override
    public void notifyPlayer(long progress) {
//        super.notifyPlayer(progress);
        //还要重启其他view的vr
        mMajorVideoHelper.startPlay(progress);
    }

    public boolean startPlayer() {
        return mMajorVideoHelper.startPlay();
    }

    public boolean consumeTouchEvent() {
        if(mVRLibrary != null && mVrHelper != null)
            return true;
        else return false;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if(mVRLibrary != null)
            mVRLibrary.onDestroy();
        if(mVrHelper != null)
            mVrHelper.onDestroy();
    }

    @Override
    public void seekTo(int progress) {
        super.seekTo(progress);
        //vr也可以拖动进度
        if(mVrHelper != null && mVrData != null) {
            int target = progress - mVrData.startSeconds*1000;
            if(target >= 0)
                mTargetPosition = target;

            Utils.Log(TAG, "VR..........seek to..." + target);
        }
    }

}